package com.kuang.utils;

import cn.hutool.log.Log;
import cn.hutool.setting.dialect.Props;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;

/**
 * @ClassName JDBCUtils
 * @Description JDBC工具类封装
 * @Author Augenestern_QXL
 * @Version 1.0
 */
@Slf4j
public class JDBCUtils {
    private  static String driverName = null;
    private  static String url = null;
    private  static String username = null;
    private  static String password = null;

    static {
        // 1. 读取src/main/resources/application.properties文件中的数据库配置
        Props props = new Props("application.properties");
        driverName = props.getStr("database.driver.name");
        url = props.getStr("database.url");
        username = props.getStr("database.username");
        password = props.getStr("database.password");

        // 1.驱动只用加载一次
        try {
            Class.forName(driverName);
        } catch (Exception e) {
            log.error("数据库驱动加载失败:",e);
        }
    }

    /**
     * 获取数据库连接,获取连接对象conn
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            log.error("数据库连接失败",e);
        }
        return conn;
    }


    /**
     * 释放连接资源
     * @param conn
     * @param ps
     * @param rs
     */
    public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (conn != null){
                conn.close();
            }
            if (ps != null){
                ps.close();
            }
            if (rs != null){
                rs.close();
            }
        }catch (Exception e){
            log.error("数据库资源关闭失败",e);
        }
    }



}
























